package com.chuangjiangx.member.basic.web.log;


import com.chuangjiangx.commons.log.AccessLogData;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求日志
 * Created by YangKuo on 17-11-7.
 */
@Aspect
@Component
@Slf4j(topic = AccessLogData.ACCESS)
public class AccessLog {

    @Around("execution(* com.chuangjiangx.member..controller..*.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        AccessLogData accessLogData = new AccessLogData(request, null);
        MDC.put("requestNO", accessLogData.getRequestNO());
        accessLogData.execBegin(log);
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Exception e) {
            accessLogData.execEnd(result, log);
            throw e;
        } finally {
            MDC.clear();//must be,threadLocal
        }
        accessLogData.execEnd(result, log);
        return result;
    }

}
